package cn.itcast.web.action;


import cn.itcast.domain.base.Area;
import cn.itcast.service.AreaService;
import cn.itcast.utils.PinYin4jUtils;
import cn.itcast.utils.ResponseUtils;
import cn.itcast.web.action.common.BaseAction;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {
    /*
    继承baseAction后 模型对象为<Area>
    baseAction提供接受的参数
     model   Area
     page    Integer
     rows    Integer
     */
    @Autowired
    private AreaService areaService;


    private File file;//接受传入Excel文件


    public void setFile(File file) {
        this.file = file;
    }//area_batchImport
    //导入数据
    @Action(value = "area_batchImport")
    public String batchImport() throws IOException {
        List<Area> areas = new ArrayList<>();
        //加载excel对象
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
        //读取sheet
        HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
        //遍历sheet中每一行
        for (Row row : sheet) {
            //去掉无效数据 首行 和最后一行(会多加载一行什么数据都没有的)
            if (row.getRowNum() == 0) { //跳过首行(表头)
                continue;
            }
            if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                continue;//跳过尾行(空行)
            }
            //封装有效数据
            Area are = new Area();
            are.setId(row.getCell(0).getStringCellValue());
            are.setProvince(row.getCell(1).getStringCellValue());
            are.setCity(row.getCell(2).getStringCellValue());
            are.setDistrict(row.getCell(3).getStringCellValue());
            are.setPostcode(row.getCell(4).getStringCellValue());
            //添加地区编码和城市简码
            String province =are.getProvince();
            String city =are.getCity();
            String district=are.getDistrict();
            //处理掉最后一个字母 如 北京(市)
            province=province.substring(0,province.length()-1);
            city=city.substring(0,city.length()-1);
            district=district.substring(0,district.length()-1);
            //拼接信息 转为拼音数组
            String[]headArray=PinYin4jUtils.getHeadByString(province+city+district);
            StringBuffer stringBuffer=new StringBuffer();
            for(String headStr : headArray){
                stringBuffer.append(headStr);
            }
            //地区编码
            String shortCode =stringBuffer.toString();

            are.setShortcode(shortCode);
            //城市简码
            String cityCode=PinYin4jUtils.hanziToPinyin(are.getCity(),"");
            are.setCitycode(cityCode);
            areas.add(are);
        }
        areaService.saveBatch(areas);
        return NONE;
    }

    //条件分页 参数 province city district rows page
    @Action(value = "area_pageQuery")
    public String pageQuery(){
        //构造查询条件
        Specification<Area>specification=new Specification<Area>() {
            List<Predicate>predicates=new ArrayList<>();
            @Override
            public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if(StringUtils.isNotBlank(model.getProvince())){
                    Predicate province = cb.like(root.<String>get("province"), "%" + model.getProvince() + "%");
                    predicates.add(province);
                }
                if(StringUtils.isNotBlank(model.getCity())){
                    Predicate city = cb.like(root.<String>get("city"), "%" + model.getCity() + "%");
                    predicates.add(city);
                }
                if(StringUtils.isNotBlank(model.getDistrict())){
                    Predicate district = cb.like(root.<String>get("district"), "%" + model.getDistrict() + "%");
                    predicates.add(district);
                }

                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        Pageable pageable=new PageRequest(page-1,rows);
        Page<Area>pageData= areaService.findPageDate(specification,pageable);
        Map<String,Object> results=new HashMap<>();
        results.put("total",pageData.getTotalElements());
        results.put("rows",pageData.getContent());
        String json=JSONArray.toJSONString(results);
        ResponseUtils.responseWriter(json);//将json数据相应到页面
        return NONE;
    }
}
